package com.hiq.gogo;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.swing.JFrame;


public class Util {
	
	/**
	 * Takes an exception and writes it down into the file "error{time}.log". 
	 * After this throwing an exception.
	 * 
	 * @param e exception
	 */
	public static void processException(Exception e) {
		try {
			PrintWriter pw = new PrintWriter("error" + System.currentTimeMillis() + ".log");
			e.printStackTrace(pw);
			pw.close();
			throw new RuntimeException(e);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * Sets the form at the center of the screen.
	 * 
	 * @param frame frame to set
	 */
	public static void setFormAtTheCenter(JFrame frame) {
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		int x = (screenSize.width - frame.getWidth()) / 2;
		int y = (screenSize.height - frame.getHeight()) / 2;
		frame.setLocation(x, y);
	}
	
	/**
	 * Reads properties from the given file.
	 * @param propertiesFileName
	 * @return
	 * @throws IOException
	 */
	public static Properties readProperties(File propertiesFile) throws IOException {
		Properties p = new Properties();
		FileReader fr = new FileReader(propertiesFile);
		p.load(fr);
		fr.close();
		return p;
	}

	public static Schedule readShedule() throws IOException {
		BufferedReader br = new BufferedReader(
				new FileReader("schedule.properties"));
		Schedule res = new Schedule();
		String line;
		while ((line = br.readLine()) != null) {
			String [] parts = line.split(":");
			String time = parts[0].trim();
			String msg  = parts[1].trim();
			ScheduleItem item = new ScheduleItem(time, msg);
			res.addItem(item);
		}
		br.close();
		return res;
	}
}
